package com.course.web.component.custom;

import com.course.web.biz.WebTeacherBiz;
import com.course.web.component.base.BaseEdit;
import com.course.web.component.base.BaseGrid;
import com.course.web.component.base.EditGrid;
import com.course.web.model.TeacherVM;
import com.vaadin.data.Binder;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.TextField;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Justin on 2017/6/10.
 */
@SpringComponent
@ViewScope
public class TeacherGrid extends EditGrid<TeacherVM> {

    private final WebTeacherBiz teacherBiz;

    @Autowired
    public TeacherGrid(WebTeacherBiz teacherBiz) {
        super(TeacherVM.class);
        this.teacherBiz = teacherBiz;
    }

    @Override
    protected void doInitMenu(Layout menu) {
        Button create = new Button("添加");
        menu.addComponent(create);
        create.addClickListener(event -> createShow());
    }

    @Override
    protected void doInitGrid(BaseGrid<TeacherVM> grid) {
        grid.addColumn(TeacherVM::getUsername, "用户名");
        grid.addColumn(TeacherVM::getName, "姓名");
        grid.addButton(this::updateShow, "编辑");
        grid.addButton(this::delete, "删除");
    }

    @Override
    protected void doInitEdit(BaseEdit<TeacherVM> edit) {
        FormLayout form = new FormLayout();
        TextField username = new TextField("用户名");
        TextField password = new TextField("密码");
        TextField name = new TextField("老师姓名");
        form.addComponent(username);
        form.addComponent(password);
        form.addComponent(name);
        form.setMargin(false);
        Binder<TeacherVM> binder = edit.binder();
        binder.bind(username, "username");
        binder.bind(password, "password");
        binder.bind(name, "name");
        edit.initEdit(form);
    }

    @Override
    protected TeacherVM doCreate() {
        return new TeacherVM();
    }

    @Override
    protected TeacherVM doCreate(TeacherVM item) {
        return teacherBiz.create(item);
    }

    @Override
    protected TeacherVM doUpdate(TeacherVM item) {
        return teacherBiz.update(item);
    }

    @Override
    protected TeacherVM doDelete(TeacherVM item) {
        return teacherBiz.delete(item);
    }

    public void enter() {
        init(teacherBiz.list());
    }
}
